﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CSP.Receipts.Business;
using CSP.Receipts.DataModel;
using MvcPaging;
using System.Web.Routing;

namespace MySharpReceipts.Controllers
{
    public class ReceiptsController : BaseController
    {
        private IReceiptRepository repository;

        public ReceiptsController(IReceiptRepository repos)
        {
            this.repository = repos;
        }

        public IQueryable<Receipt> InitDataSource(string category, RouteValueDictionary valDic)
        {
            IQueryable<Receipt> receipts;
            if (string.IsNullOrWhiteSpace(category))
                receipts = repository.GetAll().OrderByDescending(rec => rec.CreationDate);
            else
            {
                valDic.Add("category", category);
                receipts = repository.GetMany(rec => rec.Category.Title == category).OrderByDescending(rec => rec.CreationDate);
            }
            return receipts;
        }

        public ActionResult Index(string category, int? page)
        {
            
            ViewBag.Category = category;
            ViewBag.Page = page;

            IQueryable<Receipt> results;
            IPagedList<Receipt> receiptPagedList;
            RouteValueDictionary valDic = new RouteValueDictionary();

            int currentPage = page.HasValue ? page.Value - 1 : 0;

            results = InitDataSource(category, valDic);

            receiptPagedList = results.ToPagedList(currentPage, PageSize);
            receiptPagedList.ValueDictionary = valDic;

            return View(receiptPagedList);
        }

        public ActionResult Details(string title, int id)
        {
            return View(repository.GetByKey(id));
        }

        public ActionResult Search(string search)
        {
            ViewBag.SearchString = search;
            var result = repository.SearchReceipts(search);
            if (result.Count() == 1)
                return RedirectToAction("Details", new { id=result.First().Id, title = result.First().Title });
            else
                return View(result);
        }
    }
}
